package com.generator.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;


import com.generator.util.GenUtils;
import com.generator.config.DynamicDataSourceHolder;
import com.generator.entity.GenScheme;
import com.generator.entity.TableColumn;
import com.generator.ex.ServiceException;
import com.generator.service.GenSchemeService;
import com.generator.service.TableColumnService;
import com.generator.util.FileDownUtil;
import com.generator.util.SysGenUtils;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.zip.ZipOutputStream;

/**
 * 生成代码
 *
 * @author ljt
 * @date 2020-05-14 22:44:46
 */
@RestController
@RequestMapping("/genscheme" )
@Api(value = "genscheme", tags = "genscheme管理")
public class GenSchemeController {

    @Autowired
    private GenSchemeService genSchemeService;
    @Autowired
    private TableColumnService tableColumnService;


    /**
     *  生成代码
     * @param id
     * @param type
     */
    @SneakyThrows(Exception.class)
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/generator/{type}/{id}")
//    @PreAuthorize("@pms.hasPermission('generator_genscheme_add')")
    public void  generator(@PathVariable("type") Integer type, @PathVariable("id") Long id) {
        GenScheme byId = genSchemeService.getById(id);
        DynamicDataSourceHolder.setDataSourceType(Long.toString(byId.getSourceId()));
        List<TableColumn> tableColumnList = tableColumnService.getTableColumnList(byId.getTableName());

        // 获取表信息
        if (StrUtil.isBlank(byId.getRemark())) {
            String tableComment = tableColumnService.queryTableInfo(byId.getTableName());
            byId.setRemark(tableComment);
        }
        if (StrUtil.isBlank(byId.getClassName())) {
            String tableName = byId.getTableName();
            byId.setClassName(StrUtil.upperFirst(StrUtil.toCamelCase(tableName)));
        }

        DynamicDataSourceHolder.clearDataSourceType();
        if (CollUtil.isEmpty(tableColumnList)) {
            throw new ServiceException("表名不能为空！");
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(out);

        // 生成代码 前端
        if (type.equals(1)) {
            GenUtils.generatorCode(byId, tableColumnList, zip);
        } else {
            SysGenUtils.generatorCode(byId, tableColumnList, zip);
        }

        IoUtil.close(zip);

        FileDownUtil.write( byId.getTableName()+".zip", out.toByteArray());
    }

    @GetMapping("/get")
    public String get(){
        return "hi";
    }
}
